<?php

function soil_info_add_page($id)
{
    return drupal_get_form('soil_info_edit_form',$id);
}

function soil_info_edit_page($id)
{
    return drupal_get_form('soil_info_edit_form', $id);
}

function soil_info_edit_form($form, &$form_state)
{
    if (!empty($_GET['farmer_id'])) {
        $form_state['farmer'] = $_GET['farmer_id'];
    }
    if (!empty($form_state['farmer'])) {
        $form['#farmer'] = $form_state['farmer'];
    }
    drupal_add_js(drupal_get_path('module', 'fertilizer_case') . '/fertilizer_case_add_sub_extra.js', 'file');
    global $user;
    $user_info = _get_user_info($user->uid);
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    if (!empty($id)) {
        $record = nonghua_data_load('soil_info', 'soil_info_id', $id);
        if (empty($record)) {
            drupal_set_message(t('土壤信息不存在！'), 'status', FALSE);
            return $form;
        }
        $form['#soil_info_id'] = $id;
    }
    // 判断用户角色
    if(!nonghua_user_access('soil_info', 'view', $id, !empty($record) ? $record->author_uid:0, !empty($record)?$record->farmer_id:0) ){
        drupal_set_message(t('您没有权限查看本条数据！'), 'status', FALSE);
        return $form;
    }
    if ($user_info['role'] === '农户') {
        $form['farmer_id'] = array(
            '#type' => 'hidden',
            '#value' => $user->uid,
        );
    } else {
        _insert_farmer_select_info($form,$form_state,$record);

    }
    $form['basic_info'] = array(
//    '#type' => 'fieldset',
//    '#title' => '实验信息',
//    '#collapsed' => true,
//    '#collapsible' => true,
    );

    $form['submit_id'] = array(
        '#prefix' => '<div id="add_fertilizer_extra_submit-wrapper-div">',
        '#suffix' => '</div>',
        '#type' => 'hidden',
        '#title' => 'ids',
    );
    insert_fertilizer_sub_info($form, $form_state, "fertilizer_recommendation");
    insert_special_activities($form,$form_state,$record);
    $form['dif_column_id'] = array(
        '#type' => 'hidden',
        '#title' => 'id',
        '#default_value' => !empty($record) ? $record->soil_info_id : ''
    );

//    $form['basic_info']['title'] = array(
//        '#type' => 'textfield',
//        '#title' => '实验标题',
//        '#default_value' => !empty($record) ? $record->title : '',
//        '#size' => 32,
//        '#maxlength' => 20,
//    );

    $form['basic_info']['location'] = array(
        '#type' => 'textfield',
        '#title' => '实验地点',
        '#default_value' => !empty($record) ? $record->location : '',
        '#size' => 32,
        '#maxlength' => 50,
    );

    $form['basic_info']['sampler'] = array(
        '#type' => 'textfield',
        '#title' => '送样人',
        '#default_value' => !empty($record) ? $record->sampler : '',
        '#size' => 32,
        '#maxlength' => 20,
        '#id'=>'sampler'
    );

    $form['basic_info']['sample_date'] = array(
        '#title' => '采样日期',
        '#type' => 'metercomm_date',
        '#default_value' => _date_db_2_form(!empty($record) ? $record->sample_date : ''),
    );

    $form['basic_info']['target_yield'] = array(
        '#type' => 'textfield',
        '#title' => '目标产量（千克/亩）',
        '#default_value' => !empty($record) ? $record->target_yield : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );

    $form['basic_info']['pre_plant_id']= _get_plant(!empty($record) ? $record->pre_plant_id : '');
    $form['basic_info']['rec_plant_id']= _get_plant(!empty($record) ? $record->rec_plant_id : '',true,'extra');

    $form['data'] = array(
//    '#type' => 'fieldset',
//    '#title' => '测土数据',
//    '#collapsed' => true,
//    '#collapsible' => true,
    );

    $form['data']['nitrogen'] = array(
        '#type' => 'textfield',
        '#title' => '氮(mg/L)',
        '#default_value' => !empty($record) ? $record->nitrogen : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );

    $form['data']['phosphorus'] = array(
        '#type' => 'textfield',
        '#title' => '磷(mg/L)',
        '#default_value' => !empty($record) ? $record->phosphorus : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );

    $form['data']['potassium'] = array(
        '#type' => 'textfield',
        '#title' => '钾(mg/L)',
        '#default_value' => !empty($record) ? $record->potassium : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );

    $form['data']['organicmatter'] = array(
        '#type' => 'textfield',
        '#title' => '有机质(mg/L)',
        '#default_value' => !empty($record) ? $record->organicmatter : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );

    $form['data']['ph'] = array(
        '#type' => 'textfield',
        '#title' => 'PH值',
        '#default_value' => !empty($record) ? $record->ph : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );

    $form['data']['calcium'] = array(
        '#type' => 'textfield',
        '#title' => '钙(mg/L)',
        '#default_value' => !empty($record) ? $record->calcium : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );

    $form['data']['magnesium'] = array(
        '#type' => 'textfield',
        '#title' => '镁(mg/L)',
        '#default_value' => !empty($record) ? $record->magnesium : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );
    $form['data']['sulfur'] = array(
        '#type' => 'textfield',
        '#title' => '硫(mg/L)',
        '#default_value' => !empty($record) ? $record->sulfur : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );
    $form['data']['zinc'] = array(
        '#type' => 'textfield',
        '#title' => '锌(mg/L)',
        '#default_value' => !empty($record) ? $record->zinc : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );
    $form['data']['copper'] = array(
        '#type' => 'textfield',
        '#title' => '铜(mg/L)',
        '#default_value' => !empty($record) ? $record->copper : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );
    $form['data']['iron'] = array(
        '#type' => 'textfield',
        '#title' => '铁(mg/L)',
        '#default_value' => !empty($record) ? $record->iron : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );
    $form['data']['boron'] = array(
        '#type' => 'textfield',
        '#title' => '硼(mg/L)',
        '#default_value' => !empty($record) ? $record->boron : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );
    $form['data']['manganese'] = array(
        '#type' => 'textfield',
        '#title' => '锰(mg/L)',
        '#default_value' => !empty($record) ? $record->manganese : 0,
//    '#size' => 32,
//    '#maxlength' => 8,
    );
    $form['#fertilization'] = array("#markup" => fertilization_list('fertilizer_recommendation', 'soil_info_id', $id));
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => '提交',
        '#access' => nonghua_user_access('soil_info', 'edit', $id, !empty($record) ? $record->author_uid:0, !empty($record)?$record->farmer_id:0)
    );
    return $form;
}

function soil_info_edit_form_validate($form, &$form_state)
{
    if (empty($form_state['values']['farmer_id'])) {
        form_set_error('farmer', '必须选择 农户');
    }
    if (!empty($form_state['values']['target_yield'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['target_yield']) || (strlen(explode('.', $form_state['values']['target_yield'])[0]) > 8)) {
            form_set_error('target_yield', "目标产量格式错误");
        }
    }

    if (!empty($form_state['values']['nitrogen'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['nitrogen']) || (strlen(explode('.', $form_state['values']['nitrogen'])[0]) > 8)) {
            form_set_error('nitrogen', "氮格式错误");
        }
    }

    if (!empty($form_state['values']['phosphorus'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['phosphorus']) || (strlen(explode('.', $form_state['values']['phosphorus'])[0]) > 8)) {
            form_set_error('phosphorus', "磷格式错误");
        }
    }

    if (!empty($form_state['values']['potassium'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['potassium']) || (strlen(explode('.', $form_state['values']['potassium'])[0]) > 8)) {
            form_set_error('potassium', "钾格式错误");
        }
    }

    if (!empty($form_state['values']['organicmatter'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['organicmatter']) || (strlen(explode('.', $form_state['values']['organicmatter'])[0]) > 8)) {
            form_set_error('organicmatter', "有机质格式错误");
        }
    }

    if (!empty($form_state['values']['ph'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['ph']) || (strlen(explode('.', $form_state['values']['ph'])[0]) > 8)) {
            form_set_error('ph', "PH格式错误");
        }
    }

    if (!empty($form_state['values']['calcium'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['calcium']) || (strlen(explode('.', $form_state['values']['calcium'])[0]) > 8)) {
            form_set_error('calcium', "钙格式错误");
        }
    }

    if (!empty($form_state['values']['magnesium'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['magnesium']) || (strlen(explode('.', $form_state['values']['magnesium'])[0]) > 8)) {
            form_set_error('magnesium', "镁格式错误");
        }
    }

    if (!empty($form_state['values']['sulfur'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['sulfur']) || (strlen(explode('.', $form_state['values']['sulfur'])[0]) > 8)) {
            form_set_error('sulfur', "硫格式错误");
        }
    }

    if (!empty($form_state['values']['zinc'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['zinc']) || (strlen(explode('.', $form_state['values']['zinc'])[0]) > 8)) {
            form_set_error('zinc', "锌格式错误");
        }
    }

    if (!empty($form_state['values']['copper'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['copper']) || (strlen(explode('.', $form_state['values']['copper'])[0]) > 8)) {
            form_set_error('copper', "铜格式错误");
        }
    }

    if (!empty($form_state['values']['iron'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['iron']) || (strlen(explode('.', $form_state['values']['iron'])[0]) > 8)) {
            form_set_error('iron', "铁格式错误");
        }
    }

    if (!empty($form_state['values']['boron'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['boron']) || (strlen(explode('.', $form_state['values']['boron'])[0]) > 8)) {
            form_set_error('boron', "硼格式错误");
        }
    }

    if (!empty($form_state['values']['manganese'])) {
        $reg = '/^\d{1,8}(.\d{0,2})?$/';
        if (!preg_match($reg, $form_state['values']['manganese']) || (strlen(explode('.', $form_state['values']['manganese'])[0]) > 8)) {
            form_set_error('manganese', "锰格式错误");
        }
    }
    if(!empty($form_state['values']['rec_plant_id'])){
        $plant_id = get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['pre_plant_id'],false);
        if(empty($plant_id)){
            form_set_error('rec_plant_id', "作物信息不存在！");
        }
    }
    if(!empty($form_state['values']['rec_plant_id'])){
        $plant_id = get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['rec_plant_id'],false);
        if(empty($plant_id)){
            form_set_error('rec_plant_id', "作物信息不存在！");
        }
    }

}

function soil_info_edit_form_submit($form, &$form_state)
{
    global $user;
    $id = isset($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : NULL;
    clear_search_autocomplete_cach();
    if (arg(2) == 'add') {
        $nid = db_insert('soil_info')
            ->fields(array(
                'farmer_id' => $form_state['values']['farmer_id'],
                'title' => $form_state['values']['title']?$form_state['values']['title']:'',
                'location' => $form_state['values']['location'],
                'special_activities_id'=>get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities']),
                'sampler' => $form_state['values']['sampler'],
                'pre_plant_id' =>get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['pre_plant_id'],false),
                'rec_plant_id' => get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['rec_plant_id'],false),
                'sample_date' => _date_form_2_db($form_state['values']['sample_date']),
                'target_yield' => _empty_2_zero($form_state['values']['target_yield']),
                'nitrogen' => _empty_2_zero($form_state['values']['nitrogen']),
                'phosphorus' => _empty_2_zero($form_state['values']['phosphorus']),
                'potassium' => _empty_2_zero($form_state['values']['potassium']),
                'organicmatter' => _empty_2_zero($form_state['values']['organicmatter']),
                'ph' => _empty_2_zero($form_state['values']['ph']),
                'calcium' => _empty_2_zero($form_state['values']['calcium']),
                'magnesium' => _empty_2_zero($form_state['values']['magnesium']),
                'sulfur' => _empty_2_zero($form_state['values']['sulfur']),
                'zinc' => _empty_2_zero($form_state['values']['zinc']),
                'copper' => _empty_2_zero($form_state['values']['copper']),
                'iron' => _empty_2_zero($form_state['values']['iron']),
                'boron' => _empty_2_zero($form_state['values']['boron']),
                'manganese' => _empty_2_zero($form_state['values']['manganese']),
                'author_uid' =>  $user->uid,
                'timestamp' => time(),
            ))
            ->execute();
        if ($nid > 0) {
            $ids = explode(',', $form_state['values']['submit_id']);
//            print_r($ids);die;
            foreach ($ids as $key => $val) {
                $res = db_update('fertilizer_recommendation')
                    ->fields(array(
                        'soil_info_id' => $nid,
//                        'author_uid' => $user->uid,
                        'timestamp' => time(),
                    ))
                    ->condition('id', $val, '=')
                    ->execute();
            }
            drupal_set_message(t('添加成功！'), 'status', FALSE);
            if(!empty($_GET['farmer_id'])){
                drupal_goto('farmer/soil_info/add/'.$nid,array('query' => array('farmer_id' => $_GET['farmer_id'])));
            }
            if(!empty($_GET['addr_id'])){
                drupal_goto('farmer/soil_info/list',array('query' => array('addr_id' => $_GET['addr_id'])));
            }
            drupal_goto('farmer/soil_info/add/'.$nid);
        }
    } else {
        $nid = db_update('soil_info')
            ->fields(array(
                'farmer_id' => $form_state['values']['farmer_id'],
                'title' => $form_state['values']['title']?$form_state['values']['title']:'',
                'location' => $form_state['values']['location'],
                'special_activities_id'=>get_id_from_string_field('special_activities','special_activities_id','title',$form_state['values']['special_activities']),
                'sampler' => $form_state['values']['sampler'],
                'pre_plant_id' =>get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['pre_plant_id'],false),
                'rec_plant_id' =>get_id_from_string_field('plant','plant_id','plant_name',$form_state['values']['rec_plant_id'],false),
                'sample_date' => _date_form_2_db($form_state['values']['sample_date']),
                'target_yield' => _empty_2_zero($form_state['values']['target_yield']),
                'nitrogen' => _empty_2_zero($form_state['values']['nitrogen']),
                'phosphorus' => _empty_2_zero($form_state['values']['phosphorus']),
                'potassium' => _empty_2_zero($form_state['values']['potassium']),
                'organicmatter' => _empty_2_zero($form_state['values']['organicmatter']),
                'ph' => _empty_2_zero($form_state['values']['ph']),
                'calcium' => _empty_2_zero($form_state['values']['calcium']),
                'magnesium' => _empty_2_zero($form_state['values']['magnesium']),
                'sulfur' => _empty_2_zero($form_state['values']['sulfur']),
                'zinc' => _empty_2_zero($form_state['values']['zinc']),
                'copper' => _empty_2_zero($form_state['values']['copper']),
                'iron' => _empty_2_zero($form_state['values']['iron']),
                'boron' => _empty_2_zero($form_state['values']['boron']),
                'manganese' => _empty_2_zero($form_state['values']['manganese']),
//                'author_uid' => $user->uid,
                'timestamp' => time(),
            ))
            ->condition('soil_info_id', $id, '=')
            ->execute();
        if ($nid > 0) {
            drupal_set_message(t('修改成功！'), 'status', FALSE);
        }
        if(!empty($_GET['farmer_id'])){
            drupal_goto('farmer/soil_info/list',array('query' => array('farmer_id' => $_GET['farmer_id'])));
        }
        if(!empty($_GET['addr_id'])){
            drupal_goto('farmer/soil_info/list',array('query' => array('addr_id' => $_GET['addr_id'])));
        }
    }
}
